layui.config({
    base: '../js/ext/'
}).extend({
    xmSelect: 'xmselect/xm-select'
}).use(['xmSelect','tree','table','layer','form','layedit', 'laydate','util'] ,function(){
    var tree = layui.tree;
    var table=layui.table;
    var layer=layui.layer;
    var form = layui.form;
    var xmSelect = layui.xmSelect;

    form.render();

    var datab;
    //渲染
    tree.render({
        elem: '#menu'  ,//绑定元素
        showLine: false,
        data: getdata(),
        click: function(obj){
            datab=obj.data;
            console.log(datab);

            //根据二级分类和三级分类
            if( datab.catLevel==3||datab.catLevel==2){
                getAll(datab.catId);
            }
        }
    });

    table.render({
        elem: '#pmtmenu'
        ,url:''
        ,toolbar:'#toolbarDemo'
        ,defaultToolbar:[]
        ,width:900
        ,height:550
        ,id:'attrg'
        ,page:true
        ,cols: [[
            {type: 'checkbox'}
            ,{field:'attrid', width:100, title: '属性名'}
            ,{field:'searchtype', width:80, title: '可检索'}
            ,{field:'icon', width:80, title: '图标'}
            ,{field:'attrtype', width:80, title: '值类型'}
            ,{field:'valueselect', title: '可选值', width: 80}
            ,{field:'enable', title: '启用状态', width: 100}
            ,{field:'catelogid', title: '所属分类', width: 100}
            ,{field:'attrname', title: '所属分组', width: 100}
            ,{field:'showdesc', title: '快速展示', width: 100}
            ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:130}
        ]],
        data:[]
    });

    //渲染多选
    var valueselect=xmSelect.render({
        el: '#valueselect',
        filterable: true,
        create: function(val, arr){
            if(arr.length === 0){
                return {
                    name:  val,
                    value: val
                }
            }
        },
        data: []
    });

    //监听行工具事件
    table.on('tool(pmtmenu)', function(obj){
        var data=obj.data;

        //修改
        if(obj.event==='attrup') {
            var k;
            $.ajax({
                type:"post",
                //回显路径
                url:"/product/pmsspu/getValueSelect",
                data:{
                    valueselect:data.valueselect
                },
                dataType:"json",
                success:function(data) {
                    //修改回显值   data格式一定为[{name: '张三'},{name:'李四'}]
                   k=valueselect.setValue(data.data);
                }

            });
            layer.open({
                area: ["700px", "600px"],
                type: 2,
                content:'/static/subpage/Attr_Ground/Attr_pmt_edit.html',
                title: "修改",
                success:function (layero, index) {
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']]; // 得到iframe页的窗口对象
                    //回显可选值
                    body.find('#valueselect').val(k);
                    //
                    iframeWin.layui.form.render();
                }
            })

        }
        //删除
            else if (obj.event==='delete'){
                var agid=data.agid;
                $.ajax({
                    type:"post",
                    url:"",
                    data:{
                        agid:agid
                    },
                    dataType:"json",
                    success:function (data) {
                        if (data == 0) {
                            layer.msg('删除失败！',{icon:5,offset:"auto",time:2000});//提示框
                        }else{
                            layer.msg('删除成功！',{icon:6,offset:"auto",time:2000});//提示框
                        }
                        setTimeout(function(){
                            location.reload();//重新加载页面
                        }, 2100);
                    }
                })
            }

    });

    //监听头工具事件
    table.on('toolbar(pmtmenu)',function(obj){
        var data=obj.data;
        //批量删除
        if (obj.event==='pdelete'){
            layer.confirm('确定要删除吗？',function (index) {
                var checkStatus = table.checkStatus('attrg')
                    ,checkData = checkStatus.data,
                    delList=[];
                for (var i = 0; i < checkData.length; i++) {
                    delList.push(checkData[i].agid);
                }
                //json对象
                var strify = JSON.stringify(delList);
                console.log(delList);
                console.log(strify);
                $.ajax({
                    url:"",
                    dataType:'json',
                    data:{
                        datas:strify
                    },
                    type:'post',
                    success:function(data){
                        if (data == 0) {
                            layer.msg('删除失败！',{icon:5,offset:"auto",time:2000});//提示框
                        }else{
                            layer.msg('删除成功！',{icon:6,offset:"auto",time:2000});//提示框
                        }

                        setTimeout(function(){
                            location.reload();//重新加载页面表格
                        }, 2100);
                    }
                });
                // return false;
            });
        }else if(obj.event==='add'){
            layer.open({
                area:["700px","600px"],
                type:2,
                title:'新增',
                content:'/static/subpage/Attr_Ground/Attr_pmt_add.html'


            });
        }else if (obj.event==='csp'){
            //根据二级分类和三级分类查询
            if (datab.catLevel==3||datab.catLevel==2){
                getAll(datab.catId);
            }
        }

    });



    //根据查询条件查询
    function getAll(d){

        var key=$("#key").val();

        table.reload('attrg',{
            method:"get",
            url:"/product/pmsspu/attr",
            where:{
                cid:d,
                key:key
            }
        });
    }


    function getdata(){
        var data=[];
        $.ajax({
            url:'/product/pmscategory/list/tree',
            type:'get',
            async:false,
            success:function(databack){
                let kd=changeTreeDate(databack, 'title', 'name');
                data=kd;
            }

        });
        return data.data;
    }



    /**
     * 修改json数据key名称的方法
     * params date <array> 需要修改的json格式的数组
     * params newKey <string> 需要修改成的key值
     * params oldKey <string> 需要被修改的key值
     */
    function changeTreeDate(zf_jsonObj, newKey, oldKey) {
        let str = JSON.stringify(zf_jsonObj);
        let reg = new RegExp(oldKey, 'g');
        let newStr = str.replace(reg, newKey);
        return JSON.parse(newStr);
    }








});








